package baseTest;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class orangeRotting {
    public static void main(String[] args) {
        // int[][] grid = {{2,1,1},{1,1,0},{0,1,1}};
        int[][] grid = {{0,2}};
        System.out.println(process(grid));
    }

    public static int process(int[][] grid){
        int M = grid.length;
        int N = grid[0].length;
        Queue<int[]> queue = new LinkedList<>();
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 2){
                    queue.add(new int[]{i,j});
                } else if (grid[i][j] == 1){
                    count++;
                }
            }
        }
        int round = 0;
        while (count > 0 && !queue.isEmpty()){
            round++;
            for (int i = 0; i < queue.size(); i++) {
                int[] orange = queue.poll();
                int r = orange[0];
                int c = orange[1];
                if (r-1 >= 0 && grid[r-1][c] == 1){
                    grid[r-1][c] = 2;
                    count--;
                    queue.add(new int[]{r-1,c});
                }
                if (r+1 >= 0 && grid[r+1][c] == 1){
                    grid[r+1][c] = 2;
                    count--;
                    queue.add(new int[]{r+1,c});
                }
                if (c+1 >= 0 && grid[c+1][c] == 1){
                    grid[c+1][c] = 2;
                    count--;
                    queue.add(new int[]{r,c+1});
                }
                if (c-1 >= 0 && grid[c-1][c] == 1){
                    grid[c-1][c] = 2;
                    count--;
                    queue.add(new int[]{r,c-1});
                }
            }
        }
        if (count > 0){
            return -1;
        } else {
            return round;
        }
    }
}
